package com.sptpc.learspring.service;

import com.sptpc.learspring.commom.OrderState;
import com.sptpc.learspring.model.Drink;
import com.sptpc.learspring.model.Order;
import com.sptpc.learspring.repository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    public Order saveOrder(String customer, Drink... drinks) {
        Order order = Order.builder()
                .customer(customer)
                .items(new ArrayList<>(Arrays.asList(drinks)))
//                .state(OrderState.INIT).build();
                .state(OrderState.INIT).build();
        return orderRepository.save(order);
    }

    public List<Order> getOrders(String customer) {
        return orderRepository.findOrdersByCustomerLike(customer);
    }

    public Order updateOrder(long orderId, Drink deleteDrink) {
        Order order = orderRepository.findById(orderId).get();
        List<Drink> newItems = order.getItems().stream()
                .filter(drink -> drink.getId()!= deleteDrink.getId())
                .collect(Collectors.toList());
        order.setItems(newItems);
        return orderRepository.saveAndFlush(order);
    }

    public void delete(long orderId) {
        orderRepository.deleteById(orderId);
    }

    public boolean changeState(Order oldOrder, OrderState state) {
        if (state.compareTo(oldOrder.getState())<=0) {
            log.warn("状态不能从{}到{}", oldOrder.getState(), state);
            return false;
        }
        oldOrder.setState(state);
        Order order = orderRepository.saveAndFlush(oldOrder);
        log.info("更改后的订单{}", order);
        return true;
    }

}